package com.example.uupaymuch.controller.notice.east;

import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import com.alibaba.fastjson.JSONObject;
import com.example.uupaymuch.controller.util.VerifySignUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class EastPayComponent {

    private final String noticePay = "http://localhost:27003/api/pay/notify/colombiapay/eastpay";
    //    private final String noticePay = "https://pay-india.ssonicpay.com/api/pay/notify/brazilpay/wudipay";
    private static final String HMAC_SECRET = "041a3722-81b6-44db-8073-1632a9f3b9d2"; // 从安全配置中获取
    //    private final Random random = new Random();
//    private final double successProbability = 0.5; // 50% 的成功概率
    private final CloseableHttpClient httpClient;

    @Autowired
    private VerifySignUtil verifySignUtil;

    public EastPayComponent() {
        // 创建带有连接池的 HttpClient 实例
        this.httpClient = HttpClients.custom()
                .setMaxConnTotal(200)  // 设置最大连接数
                .setMaxConnPerRoute(200)  // 设置每个路由的最大连接数
                .build();
    }

    ScheduledThreadPoolExecutor scheduledThreadPoolExecutorTransfer =
            new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 2);

    public void doNotifyPay(String txid, String text, String amount) {
        scheduledThreadPoolExecutorTransfer.schedule(() -> {
            // 执行推送
            try {
                notifyPaymentPay(txid, text, amount);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }, 1, TimeUnit.SECONDS);
    }

    public void notifyPaymentPay(String payOrderId, String text, String amount) throws IOException {
        Map<String, Object> params = new HashMap<>();
        params.put("partner_trx_id", payOrderId);
        params.put("status", text);

        // 补充字段
        params.put("merchant_id", "MSF20240110090214000");
        params.put("plat_trx_id", "PB1745988627755831296");
        params.put("type", 0); // 付款订单类别
        params.put("amount", amount); // 账单金额
        params.put("plat_fee", "3000.00"); // 平台手续费
        params.put("method", "Pse"); // 支付方式
        params.put("status_msg", "Payment Succeed"); // 状态描述
        params.put("success_time", "2023-11-18 09:58:01"); // 可选字段
        JSONObject jsonObject = new JSONObject(params);
        try {
            HttpPost request = new HttpPost(noticePay);

            String signature = verifySignUtil.verifySign(jsonObject, HMAC_SECRET);
            params.put("signature", signature); // 签名字符串，请替换为实际签名
            String json = new ObjectMapper().writeValueAsString(params);
            StringEntity entity = new StringEntity(json);
            entity.setContentType("application/json");
            request.setEntity(entity);

            CloseableHttpResponse response = httpClient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                log.error("Failed to notify payment. HTTP Status: {}", statusCode);
            }
        } catch (Exception e) {
            throw new RuntimeException("代收回调异常:", e);
        }
    }



}
